<script>
  // 使用 JavaScript 动态加载 SVG 文件
  fetch("public/icons/search-svgrepo-com.svg") // SVG 文件路径
    .then((response) => response.text())
    .then((svg) => {
      document.getElementById("icon-container").innerHTML = svg;
    });
</script>

<div class="search-container">
  @if (loading) {
    <mat-progress-bar mode="buffer" class="search-bar"></mat-progress-bar>
  } @else {
    <form [formGroup]="searchForm" (submit)="onSearch()" class="search-form">
      <input
        formControlName="query"
        type="text"
        placeholder="Search..."
        class="search-input"
      />
      <button type="submit" class="icon-button" title="Search">
        <icon-search></icon-search>
      </button>
    </form>
  }
</div>

<!-- Material 表格 -->
<table
  mat-table
  [dataSource]="dataSource"
  matSort
  (matSortChange)="onSort($event)"
  class="mat-elevation-z8"
>
  <!-- 定义表头行 -->
  @for (column of columns; track column) {
    <ng-container [matColumnDef]="column">
      <!-- 表头单元格 -->
      <th mat-header-cell *matHeaderCellDef mat-sort-header>
        {{ column | titleCase }}
      </th>
      <!-- 数据单元格 -->
      <td mat-cell *matCellDef="let item">
        @if (isDateColumn(column)) {
          <!-- 如果是 Date 类型,则进行时间格式转换 -->
          {{ item[column] | dateFnsTz }}
        } @else if (column === "options") {
          <ng-container>
            <!-- Options SVG 图标 -->
            <button mat-icon-button [matMenuTriggerFor]="optionsMenu" >
              <img
                ngSrc="icons/options-svgrepo-com.svg"
                alt="Options"
                title="Options"
                width="24"
                height="24"
              />
            </button>
            <!-- Options 菜单 -->
            <mat-menu #optionsMenu="matMenu" class="options-popup">
              <button mat-menu-item (click)="onDelete(item['hash'])">
                <img
                  ngSrc="icons/delete-2-svgrepo-com.svg"
                  alt="Delete" class="option-item"
                  title="Delete"
                  width="24"
                  height="24"
                />
              </button>
            </mat-menu>
          </ng-container>
        } @else {
          {{ item[column] || "N/A" }}
        }
      </td>
    </ng-container>
  }

  <!-- 渲染表头 -->
  <tr mat-header-row *matHeaderRowDef="columns"></tr>
  <!-- 渲染数据行 -->
  <tr mat-row *matRowDef="let row; columns: columns"></tr>
</table>

<!-- 分页器 -->
<mat-paginator
  [length]="total"
  [pageSize]="pageSize"
  [pageIndex]="pageIndex"
  [pageSizeOptions]="[5, 10, 20]"
  showFirstLastButtons
  (page)="onPageChanged($event)"
></mat-paginator>

@if (!loading && dataSource.data.length === 0) {
  <div class="no-results">No results found.</div>
}
